package com.rc.web.service.impl;


import com.fasterxml.jackson.databind.ObjectMapper;
import com.rc.web.utils.VivoAuth;
import org.springframework.http.*;
import org.springframework.http.client.ClientHttpResponse;
import org.springframework.stereotype.Service;
import org.springframework.util.StreamUtils;
import org.springframework.web.client.DefaultResponseErrorHandler;
import org.springframework.web.client.HttpClientErrorException;
import org.springframework.web.client.RestTemplate;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;

@Service
public class RerankService {
    private static final String APP_ID = "2025985389";
    private static final String APP_KEY = "eAkRKtYXOawsmtVv";
    private static final String DOMAIN = "api-ai.vivo.com.cn";
    private static final String URI = "/rerank";
    private static final String METHOD = "POST";

    public String rerank(String query,String[] sentences) throws UnsupportedEncodingException {
        try {
            // 1. 严格按照Vivo API要求的结构构建请求体
            Map<String, Object> requestBody = new LinkedHashMap<>();
            requestBody.put("model_name", "bge-reranker-large");
            requestBody.put("query", query);
            requestBody.put("sentences", Arrays.asList(sentences)); // 确保转换为List

            // 2. 打印请求体用于调试
            ObjectMapper mapper = new ObjectMapper();
            String requestJson = mapper.writeValueAsString(requestBody);
            System.out.println("Request JSON: " + requestJson);

            // 3. 生成签名头并明确设置Content-Type
            HttpHeaders headers = VivoAuth.generateAuthHeaders(APP_ID, APP_KEY, METHOD, URI, "");
            headers.setContentType(MediaType.APPLICATION_JSON);

            // 4. 创建RestTemplate并设置错误处理
            RestTemplate restTemplate = new RestTemplate();
            restTemplate.setErrorHandler(new DefaultResponseErrorHandler() {
                @Override
                protected void handleError(ClientHttpResponse response, HttpStatus statusCode) throws IOException {
                    String responseBody = StreamUtils.copyToString(response.getBody(), StandardCharsets.UTF_8);
                    throw new HttpClientErrorException(statusCode, "Vivo API Error: " + responseBody);
                }
            });

            // 5. 发送请求
            HttpEntity<String> entity = new HttpEntity<>(requestJson, headers);
            String url = "https://" + DOMAIN + URI;
            ResponseEntity<String> response = restTemplate.exchange(url, HttpMethod.POST, entity, String.class);

            return response.getBody();

        } catch (Exception e) {
            System.err.println("Error calling Vivo API:");
            e.printStackTrace();
            throw new RuntimeException("API调用失败: " + e.getMessage());
        }
    }
        // 处理响应
        /*if (response.getStatusCode().is2xxSuccessful()) {
            System.out.println(response.getBody());
        } else {
            System.out.println(response.getStatusCode() + " " + response.getBody());
        }
        return response.getBody();*/

}
